<template>
  <setting-public-view current="taskType" viewClass="setting-view-main2" :nav="taskNav">
    <div id="task-manange-guide"></div>
    <div class="task-manage-header" id="task-manage-header-guide">
      <div>
        <h2>
          {{$t('common.task.taskType')}}
          <el-tooltip
            trigger="hover"
          >
            <div slot="content" style="width: 420px">
              <h3>{{$t('common.base.rulerTip')}}</h3>
              <p>{{$t('task.setting.taskTypeSetting.manage.title1', {max: maxTypeNum})}}</p>
              <h3>{{$t('task.setting.taskTypeSetting.manage.fieldDesc')}}</h3>
              <p>{{$t('task.setting.taskTypeSetting.manage.title2')}}</p>
              <p>{{$t('task.setting.taskTypeSetting.manage.title3')}}</p>
              <p>{{$t('task.setting.taskTypeSetting.manage.title4')}}</p>
            </div>
            <i class="el-icon-question" />
          </el-tooltip>
        </h2>
        <p>{{$t('task.setting.taskTypeSetting.manage.title5')}}</p>
      </div>
      <div class="lh-52">
        <el-button type="primary" :loading="false" @click="addTaskType">
          <i class="iconfont icon-add2" style="font-size: 12px;"></i> {{$t('common.base.create')}}
        </el-button>
      </div>
    </div>
    <div class="task-type-list" id="task-type-list-guide" v-loading="pendding">
      <draggable
        v-bind="{ animation: 380, ghostClass: 'ghost' }"
        v-model="taskTypeList"
        tag="div"
        @change="updateListOrder"
        class="task-type-group"
      >
        <task-type-item
          class="task-type-item"
          v-for="item in taskTypeList"
          :key="item.id"
          :task-type="item"
          :team-list="teamList"
          :type-num="enableTypeNum"
          :max-type-num="maxTypeNum"
          @update="fetchTaskTypeList"
          @handleChooseUseDept="handleChooseUseDept(item)"
          @updateAttr="obj => {
            updateTaskType(item, obj)
          }">
          </task-type-item>
      </draggable>
    </div>

    <!-- 新建工单类型弹窗 -->
    <add-task-type-dialog :visiable.sync="isAddTaskTypeModal" :task-type-list="taskTypeList"/>

    <choose-team-confirm-dialog type="task" @submit="handleChangeUseDept" ref="chooseTeamConfirmDialog" />
  </setting-public-view>

</template>

<script>
import draggable from 'vuedraggable';

/** api */
import * as SettingApi from '@src/api/SettingApi.ts';

/** component */
import TaskTypeItem from './components/TaskTypeItem.vue';
import AddTaskTypeDialog from './components/AddTaskTypeDialog';
import SettingPublicView from '../../../components/settingPublicView';

import ChooseTeamConfirmDialog from '@src/modules/setting/serviceEvent/serviceEventTypeSetting/manage/components/ChooseTeamConfirmDialog/ChooseTeamConfirmDialog'; 

// 新存储工具方法
import { storageGet, storageSet } from '@src/util/storage.ts';
/* enum */
import StorageModuleEnum from '@model/enum/StorageModuleEnum';
/* 工单设置导航 */
import {taskNav} from '../../../components/settingPublicView/navList.js';

import { TASK_TYPE_SETTING_GUIDE } from '@src/component/guide/taskSettingStore';

import { handleChangeUseDept, handleChooseUseDept } from '@src/modules/setting/serviceEvent/serviceEventTypeSetting/manage/components/ChooseTeamConfirmDialog/utils/fetchFun'; 

export default {
  name: 'task-manage',
  data() {
    return {
      taskTypeList: [],
      teamList: [],
      maxTypeNum: 10,

      isAddTaskTypeModal: false,
      pendding: false,
      taskNav:taskNav||{},
      currentChooseDeptItemId: null
    }
  },
  computed: {
    enableTypeNum() {
      return this.taskTypeList.filter(item => item.enabled === 1).length;
    }
  },
  methods: {
    async handleChangeUseDept(params) {
      const rs = await handleChangeUseDept(params, 'task')
      if(rs) {
        this.fetchTaskTypeList()
      }
    },
    async handleChooseUseDept(typeItem) {
      handleChooseUseDept.call(this, typeItem, 'task')
    },
    updateTaskType(taskType, updateObj) {
      for (const key in updateObj) {
        if (updateObj.hasOwnProperty(key)) {
          taskType[key] = updateObj[key];
        }
      }
    },
    /** 添加工单类型 */
    addTaskType() {
      this.isAddTaskTypeModal = true;
    },
    /** 更新列表排序*/
    async updateListOrder() {
      try {
        let orderParams = {};
        this.taskTypeList.map((typeItem, idx) => {
          if (!orderParams[typeItem.id]) orderParams[typeItem.id] = idx + 1;
          return {
            id: typeItem.id,
            order: idx + 1,
          };
        });
        const res = await SettingApi.taskTypeOrder(orderParams);
        if (res.status == 0) {
          // this.$message.success('排序成功');
        }
      } catch(error) {
        console.error('updateListOrder => error', error);
      }
    },
    /** 获取工单类型列表 */
    fetchTaskTypeList() {
      this.pendding = true;
      return SettingApi.getTaskTypeManage().then((res) => {
        this.pendding = false;
        let {tagListJson, taskTypeListJson, maxTypeNum} = res;

        this.maxTypeNum = maxTypeNum;
        this.teamList = tagListJson || [];
        taskTypeListJson = taskTypeListJson || [];

        // 排序
        this.taskTypeList = taskTypeListJson.sort(
          (a, b) => (a.orderId > b.orderId && a.enabled > b.enabled));
      }).catch(err => {
        console.error('fetch taskTypeList => error', err);
      })
        .finally(() => {
          this.pendding = false;
        })
    },
  },
  async mounted() {
    await this.fetchTaskTypeList();

    // this.$nextTick(async() => {
    //   const guideStore = await storageGet(TASK_TYPE_SETTING_GUIDE, 0, StorageModuleEnum.Task);
    //   if (guideStore > 0) return this.$Guide().destroy('task-manange-guide');

    //   this.$Guide([{
    //     id: 'task-manange-guide',
    //     content: '工单类型以卡片的形式显示，一个卡片代表一个工单类型',
    //     haveStep: true,
    //     needCover: true,
    //     nowStep: 1,
    //     domObj: () => {
    //       return document.getElementById('task-manage-header-guide')
    //     },
    //     lastFinish: true
    //   }, {
    //     id: 'task-manange-guide',
    //     content: '可用「编辑」功能修改该工单类型的「可用部门」',
    //     haveStep: true,
    //     needCover: true,
    //     inside: true,
    //     nowStep: 2,
    //     domObj: () => {
    //       return document.getElementById('task-type-list-guide').getElementsByClassName('task-type-item')[0]
    //     },
    //     insideDom: () => {
    //       return document.getElementById('task-type-list-guide').getElementsByClassName('task-type-item')[0].getElementsByClassName('task-type-team-setting')[0]
    //     },
    //     lastFinish: true
    //   }], 0, '', (e) => {
    //     return new Promise((resolve, reject) => {
    //       resolve()
    //     })
    //   }).create()
    //     .then(res_ => { 
    //       if(res_) storageSet(TASK_TYPE_SETTING_GUIDE, '2', StorageModuleEnum.Task);
    //     })
    // })
  },
  components: {
    [SettingPublicView.name]: SettingPublicView,
    [TaskTypeItem.name]: TaskTypeItem,
    [AddTaskTypeDialog.name]: AddTaskTypeDialog,
    [ChooseTeamConfirmDialog.name]: ChooseTeamConfirmDialog,
    draggable
  }
}
</script>
<style lang="scss" scoped>
.task-manage-header{
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 16px 16px 0 16px;
  width: 100%;
  background: #FFFFFF;
  border-radius: 4px;
  .el-icon-question{
    color: #666666;
  }
  h2{
    margin-bottom: 10px;
    font-size: 16px;
    color: #333333;
    line-height: 22px;
  }
  p{
    font-size: 12px;
    color: #666666;
    line-height: 20px;
  }
  .lh-52{
    line-height: 52px;
  }
}
.task-type-list{
  height: calc(100% - 100px);
  overflow: auto;
  .task-type-group {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    @include dynamic-card-list(2, 'task-type-item');
    .task-type-item {
      margin: 0 12px 12px 0;
    }
  }
}

// transtion
.flip-list-move {
  transition: transform 0.5s;
}
</style>